//
//  PhotoDetailViewController.m
//  B
//
//  Created by Sunpeng on 15/11/9.
//  Copyright © 2015年 wangzhan. All rights reserved.
//

#import "PhotoDetailViewController.h"
#import "MBProgressHUD.h"
#import "ImageViewCollectionViewCell.h"
#import "HTTPTool.h"
#import "UIImageView+WebCache.h"
#import "BaseView.h"
#import "SearchDetailViewController.h"
#import "TravelDetailViewController.h"
#import "DataBaseHandle.h"
#import "BaseView.h"
@interface PhotoDetailViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic,retain)UICollectionView *collectionView;
@property(nonatomic,retain)UIButton *collectButton;
@property(nonatomic,assign)NSInteger myIndex;
@property(nonatomic,retain)MBProgressHUD *HUD;
@property(nonatomic,retain)NSMutableArray *searchTitleArray;
@property(nonatomic,retain)UIButton *mapButton;
@end

@implementation PhotoDetailViewController

-(void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    [super viewWillAppear:animated];
    for (UIView *view in self.tabBarController.view.subviews) {
        if ([view isKindOfClass:[BaseView class]]) {
            view.hidden = YES;
        }
    }

    NSUserDefaults *isCollect = [NSUserDefaults standardUserDefaults];
    [isCollect setObject:@"NO" forKey:@"collect"];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"reloadTableView" object:nil];
  
}


- (void) viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    for (UIView *view in self.tabBarController.view.subviews) {
        if ([view isKindOfClass:[BaseView class]]) {
            view.hidden = NO;
        }
    }
    
    
}



- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.imageArr = [NSMutableArray array];
        self.photo_infoArr = [NSMutableArray array];
        self.textArr = [NSMutableArray array];
        self.timeArr = [NSMutableArray array];
        self.searchTitleArray = [NSMutableArray array];
        self.hidesBottomBarWhenPushed = YES;
    }
    
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //NSLog(@"self.type = %@ %@ %ld",self.type,self.bId,self.refresh);
    self.navigationItem.title = self.titleText;
    UIImage *leftImage = [UIImage imageNamed:@"导航栏_button_back_用于白和灰.png"];
    leftImage = [leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction)];
    
    
//    UIImage *rightImage = [UIImage imageNamed:@"iconfont-ditu-2.png"];
//    rightImage = [rightImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:rightImage style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];
    
    [self createTitleView];
    [self createView];
    //NSLog(@"http://api.breadtrip.com//destination/place/%@/%@/photos/?gallery_mode=1&count=%ld&start=2",self.type,self.bId,self.count);
    [self createData];
    //NSLog(@"url = %@",self.bId);
    
}
-(void)createView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH, HIGHT-64);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT-64) collectionViewLayout:flowLayout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:self.collectionView];
    
    
    [self.collectionView registerClass:[ImageViewCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.collectionView.pagingEnabled = YES;
    
    //NSLog(@"cgpoint = %f",WIDTH*self.index);
}
-(void)leftButtonAction
{
     
    
    [self.navigationController popViewControllerAnimated:NO];
}
-(void)rightButtonAction:(UIButton *)sender
{
    TravelDetailViewController *tavel = [[TravelDetailViewController alloc]init];
    NSString *urlStr = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints/?gallery_mode=1&sign=dea21f7ed5e413c82c05a351135ed1e8",self.trip_id];
    NSLog(@"444%@",self.trip_id);
    tavel.UrlStr = urlStr;
    NSLog(@"2333%@",urlStr);
    [self.navigationController pushViewController:tavel animated:YES];
    
    
   
}

-(void)createData{
    NSLog(@"44%@ %@ %ld",self.type,self.bId,self.count);
    [HTTPTool get:[NSString stringWithFormat:@"http://api.breadtrip.com//destination/place/%@/%@/photos/?gallery_mode=1&count=%ld&start=2",self.type,self.bId,self.count] body:nil httpResult:JSON success:^(id result) {
        //http://api.breadtrip.com//destination/place/%@/%@/photos/?gallery_mode=1&count=18&start=%ld
        NSLog(@"7777--http://api.breadtrip.com//destination/place/%@/%@/photos/?gallery_mode=1&count=%ld&start=2",self.type,self.bId,self.titleArray.count);
        
        NSDictionary *dic = result;
        //NSLog(@"%@",dic);
        NSArray *itemsArr = dic[@"items"];
        for (NSDictionary *tempDic in itemsArr) {
            [self.imageArr addObject:tempDic[@"photo"]];
            [self.photo_infoArr addObject:tempDic[@"photo_info"]];
            [self.textArr addObject:tempDic[@"text"]];
            [self.timeArr addObject:tempDic[@"local_time"]];
            [self.searchTitleArray addObject:tempDic[@"trip_name"]];
            
        }
        //NSLog(@"are you righy");
        [self.HUD removeFromSuperview];
        [self.collectionView reloadData];
        self.collectionView.contentOffset=CGPointMake(WIDTH*self.index, 0);
        
        
    } failure:^(NSError *error) {
        NSLog(@"dddddd");
    }];
    self.HUD=[[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    [self.HUD showAnimated:YES whileExecutingBlock:^{
        
    } completionBlock:^{
        [self.HUD show:NO];
        
    }];
    
}

//创建视图


-(void)createTitleView
{
    if (self.titleArray.count != 0) {
        self.count = self.titleArray.count;
        
    }
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 0.066*HIGHT)];
    self.navigationItem.titleView = titleView;
    //titleView.backgroundColor = [UIColor yellowColor];
    self.collectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.collectButton.frame = CGRectMake(0.693*WIDTH-25, 10, 0.067*WIDTH, 0.037*HIGHT);
    NSMutableArray *array = [[DataBaseHandle ShareDataBaseHandle]selectImageCollectWithText];
    self.label = [[UILabel alloc]initWithFrame:CGRectMake(0.107*WIDTH, 8, 0.507*WIDTH, 0.045*HIGHT)];
    self.label.text = self.titleText;
    self.label.textColor = [UIColor whiteColor];
    self.label.textAlignment = NSTextAlignmentCenter;
    [titleView addSubview:self.label];
    
    //    NSString *picUrl = [self.imageArr objectAtIndex:self.index];
    //    NSString *text = [self.titleArray objectAtIndex:self.index];
    //    //NSLog(@"text = %@ %ld",text,self.index);
    if ([array containsObject:self.label.text]) {
        [self.collectButton setBackgroundImage:[UIImage imageNamed:@"SPiconfont-shoucang-4"] forState:UIControlStateNormal];
        
    }
    else
    {
        [self.collectButton setBackgroundImage:[UIImage imageNamed:@"SPiconfont-shoucang-3"] forState:UIControlStateNormal];
    }
    [self.collectButton addTarget:self action:@selector(collectAction:) forControlEvents:UIControlEventTouchUpInside];
    
        self.mapButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.mapButton.frame = CGRectMake(0.693*WIDTH+18, 10, 0.067*WIDTH, 0.037*HIGHT);
        [self.mapButton setBackgroundImage:[UIImage imageNamed:@"SPiconfont-ditu-2"] forState:UIControlStateNormal];
    [self.mapButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:self.mapButton];
        [titleView addSubview:self.collectButton];
    self.navigationItem.titleView = titleView;
    
}

//collectionView的两个协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    //NSLog(@"se.count = %ld",self.imageArr.count);
    return self.imageArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ImageViewCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath] ;
    
    //    设置图片的自适应以及居中放置
    NSDictionary *dic = self.photo_infoArr[indexPath.row];
    //NSLog(@"dic***** = %@",dic);
    double imageHeight = WIDTH * [dic[@"h"] doubleValue] / [dic[@"w"] doubleValue];
    cell.myImageView.frame = CGRectMake(0, 0, WIDTH, imageHeight);
    cell.myImageView.center = cell.contentView.center;
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:self.imageArr[indexPath.row]]];
    
    //  textLabel自适应
    cell.textLabel.text = self.textArr[indexPath.row];
    NSDictionary *Dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14*XHIGHT],NSFontAttributeName, nil];
    
    CGRect rect = [cell.textLabel.text boundingRectWithSize:CGSizeMake(cell.contentView.frame.size.width, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:Dic context:nil];
    cell.textLabel.frame = CGRectMake(5, 0, cell.contentView.frame.size.width, rect.size.height);
    cell.myView.frame = CGRectMake(0, cell.contentView.frame.size.height - 30*XHIGHT - cell.textLabel.frame.size.height, cell.contentView.frame.size.width, cell.textLabel.frame.size.height + 30*XHIGHT);
    cell.timeLabel.frame = CGRectMake(5, cell.myView.frame.size.height - 30*XHIGHT, 150*XWIDTH, 30*XHIGHT);
    cell.timeLabel.text = self.timeArr[indexPath.row];
    
    return cell;
}
//
////收藏
-(void)collectAction:(UIButton *)collect
{
    //    NSUserDefaults *isCollect = [NSUserDefaults standardUserDefaults];
    //    NSString *str = [isCollect objectForKey:@"collect"];
    NSMutableArray *array = [[DataBaseHandle ShareDataBaseHandle]selectImageCollectWithText];
    if (self.imageArr.count != 0 && self.titleArray.count != 0) {
        NSString *picUrl = [self.imageArr objectAtIndex:self.index];
        //        NSString *text = [self.titleArray objectAtIndex:self.myIndex];
        NSString *typeStr = [NSString stringWithFormat:@"%@",self.type];
        NSString *index = [NSString stringWithFormat:@"%ld",self.index];
        //        //NSLog(@"caole = %@",text);
        //        //NSLog(@"str = %@",str);
        
        if (![array containsObject:self.label.text] ) {
            [[DataBaseHandle ShareDataBaseHandle]insertImageTable:picUrl and:self.label.text and:self.bId and:typeStr and:index and:self.titleArray.count];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
            //            [isCollect setObject:@"YES" forKey:@"collect"];
            [collect setBackgroundImage:[UIImage imageNamed:@"SPiconfont-shoucang-4"] forState:UIControlStateNormal];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"该活动已被收藏" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
            
        }
        
    }
    
    //点击收藏进行的判断
    if (self.imageArr.count != 0 && self.titleArray.count == 0) {
        NSString *picUrl = [self.imageArr objectAtIndex:self.index];
        NSString *text = [self.searchTitleArray objectAtIndex:self.myIndex];
        NSString *typeStr = [NSString stringWithFormat:@"%@",self.type];
        NSString *index = [NSString stringWithFormat:@"%ld",self.index];
        //NSLog(@"caole = %@",text);
        //        //NSLog(@"str = %@",str);
        
        if (![array containsObject:self.label.text]) {
            [[DataBaseHandle ShareDataBaseHandle]insertImageTable:picUrl and:self.label.text and:self.bId and:typeStr and:index and:self.searchTitleArray.count];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
            //            [isCollect setObject:@"YES" forKey:@"collect"];
            [collect setBackgroundImage:[UIImage imageNamed:@"SPiconfont-shoucang-4"] forState:UIControlStateNormal];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"该活动已被收藏" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
            
        }
        
    }
    
    
}
//分享
//-(void)shareAction:(UIButton *)share
//{
//    UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[self.imageArr objectAtIndex:self.index]]]];
//    [UMSocialSnsService presentSnsIconSheetView:self
//                                         appKey:@"507fcab25270157b37000010"
//                                      shareText:self.label.text
//                                     shareImage:image
//                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,nil]
//                                       delegate:self];
//
//}



- (void)scrollViewDidEndDecelerating:(UICollectionView *)scrollView
{
    self.myIndex = ((scrollView.contentOffset.x+WIDTH) - WIDTH) / WIDTH;
    //NSLog(@"%f",scrollView.contentOffset.x);
    //NSLog(@"index = %ld",self.myIndex);
    if (self.titleArray.count == 0) {
        self.label.text = [self.searchTitleArray objectAtIndex:self.myIndex];
        //NSLog(@"what the hell");
        //NSLog(@"%@",self.label.text);
    }
    else
    {
        self.label.text = [self.titleArray objectAtIndex:self.myIndex];
    }
    
    self.index = self.myIndex;
    //NSLog(@"label,text = %@",self.label.text);
    NSMutableArray *array = [[DataBaseHandle ShareDataBaseHandle]selectImageCollectWithText];
    //    NSUserDefaults *isCollect = [NSUserDefaults standardUserDefaults];
    if (![array containsObject:self.label.text]) {
        //NSLog(@"%@",self.label.text);
        [self.collectButton setBackgroundImage:[UIImage imageNamed:@"SPiconfont-shoucang-3"] forState:UIControlStateNormal];
        //        [isCollect setObject:@"NO" forKey:@"collect"];
    }
    else
    {
        [self.collectButton setBackgroundImage:[UIImage imageNamed:@"SPiconfont-shoucang-4"] forState:UIControlStateNormal];
    }
    

       
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
